package cn.mumzone.pos.ui.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.JustifyContent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.IsFastClickUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.BindMemberEntity;
import cn.mumzone.pos.event.RefreshMemberLevelEvent;
import cn.mumzone.pos.event.SettleDiscountEvent;
import cn.mumzone.pos.event.SettleSuccessEvent;
import cn.mumzone.pos.model.BillDetailEntity;
import cn.mumzone.pos.model.DiscountMenuEntity;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.LoginEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.SettleCalculatePriceEntity;
import cn.mumzone.pos.model.SettleDiscountAreaEntity;
import cn.mumzone.pos.model.TicketEntity;
import cn.mumzone.pos.model.TimeCardEntity;
import cn.mumzone.pos.presenter.SettleAccountPresenter;
import cn.mumzone.pos.presenter.contract.SettleAccountContract;
import cn.mumzone.pos.ui.adapter.ADA_ActivityList;
import cn.mumzone.pos.ui.adapter.ADA_CouponList;
import cn.mumzone.pos.ui.adapter.ADA_DialogChooseServerList;
import cn.mumzone.pos.ui.adapter.ADA_DiscountList;
import cn.mumzone.pos.ui.adapter.ADA_DiscountMenu;
import cn.mumzone.pos.ui.adapter.ADA_TimesCard;
import cn.mumzone.pos.ui.widgets.StepView;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.AddMemberUtil;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.LedDisplayUtil;
import cn.mumzone.pos.util.MyFlexBoxLayoutManager;
import cn.mumzone.pos.util.PopupUtil;
import cn.mumzone.pos.util.print.PrintEntity;
import cn.mumzone.pos.util.print.PrinterService;

import static cn.mumzone.pos.dialog.PosDialog.CONFIRM_TYPE_WITH_TEXT_SHADOW;
import static cn.mumzone.pos.model.SettleCalculatePriceEntity.DiscountItemBean.TYPE_ACTIVITY;
import static cn.mumzone.pos.model.SettleCalculatePriceEntity.DiscountItemBean.TYPE_COUPON;
import static cn.mumzone.pos.model.SettleCalculatePriceEntity.DiscountItemBean.TYPE_TIMES_CARD;

/**
 * Created by qiuzhenhuan on 2019/6/17.
 */

public class ACT_SettleAccounts extends BaseActivity<SettleAccountPresenter> implements SettleAccountContract.View {
    //账单类型 0 服务 1 商品
    public static final String SETTLE_ORDER_TYPE_SERVICE = "0";
    public static final String SETTLE_ORDER_TYPE_GOODS = "1";
    public static final String SETTLE_ORDER_TYPE_TIMES_CARD = "2";
    public static final String SETTLE_ORDER_TYPE_BABY_SWIM = "3";

    //结算类型 0 商品 1 服务 2 计次卡
    private static final int SETTLE_SETTLE_TYPE_SERVICE = 1;
    private static final int SETTLE_SETTLE_TYPE_GOODS = 0;
    private static final int SETTLE_SETTLE_TYPE_TIMES_CARD = 2;

    private static final String SETTLE_GOODS_JSON = "settle_goods_json";
    private static final String SETTLE_GOODS_IF_SAVED = "settle_goods_if_saved";
    private static final String SETTLE_MEMBER_PHONE = "settle_member_phone";
    private static final String SETTLE_ORDER_TYPE = "order_type";


    private static final String SUNMI_PAY_ACTION = "sunmi.payment.action.result";

    private static final int REQUEST_CODE_REDEEM_GOODS = 1005;

    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_member_phone)
    TextView tvMemberPhone;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.iv_add_member)
    ImageView ivAddMember;
    @BindView(R.id.iv_member_link)
    ImageView ivUnbindMember;
    @BindView(R.id.tv_member_balance)
    TextView tvMemberBalance;
    @BindView(R.id.tv_member_points)
    TextView tvMemberPoints;
    @BindView(R.id.rl_member_layout)
    RelativeLayout rlMemberBind;
    @BindView(R.id.rl_member_unbind)
    RelativeLayout rlMemberUnBind;
    @BindView(R.id.tv_member_waiter)
    TextView tvMemberWaiter;

    @BindView(R.id.tv_origin_amount)
    TextView tvOriginAmount;
    @BindView(R.id.rl_bargain)
    RelativeLayout rlBargain;
    @BindView(R.id.tv_bargain)
    TextView tvBargain;
    @BindView(R.id.rl_goods_discount)
    RelativeLayout rlGoodsDiscount;
    @BindView(R.id.tv_goods_discount)
    TextView tvGoodsDiscount;
    @BindView(R.id.tv_member_discount)
    TextView tvMemberDiscount;
    @BindView(R.id.rl_present)
    RelativeLayout rlPresent;
    @BindView(R.id.tv_present)
    TextView tvPresent;

    @BindView(R.id.rv_discount_menu)
    RecyclerView rvDiscountMenu;


    @BindView(R.id.rv_discount_list)
    RecyclerView rvDiscountList;
    @BindView(R.id.tv_result_amount)
    TextView tvResultAmount;
    @BindView(R.id.btn_settle)
    LoadingButton btnConfirmPay;

    @BindView(R.id.rl_cash_pay_bg)
    RelativeLayout rlCashPay;
    @BindView(R.id.rl_balance_pay_bg)
    RelativeLayout rlBalancePay;
    @BindView(R.id.rl_ali_pay_bg)
    RelativeLayout rlAliPay;
    @BindView(R.id.rl_wx_pay_bg)
    RelativeLayout rlWxPay;
    @BindView(R.id.rl_card_pay_bg)
    RelativeLayout rlCardPay;
    @BindView(R.id.rl_integral_pay_bg)
    RelativeLayout rlIntegralPay;
    @BindView(R.id.btn_ml)
    Button btnMl;

    // 从上个页面携带过来的数据
    private String goodsJson;
    private boolean ifGoodsSaved;
    private String phone = "";
    private String orderType = "";
    private String settleType = "";
    private String memberIntegral = "";


    //选择会员&添加会员
    private PosAlertDialog unBindMemberDialog;
    private boolean isUnbindMember;

    private AlertDialog chooseServerDialog;
    private LRecyclerView rvServerList;
    private ADA_DialogChooseServerList mServerAdapter;


    private ADA_DiscountMenu mDiscountMenuAdapter;

    //优惠信息
    private ADA_DiscountList mDiscountAdapter;
    private PosAlertDialog cancelDiscountDialog;

    //次卡
    private AlertDialog cardDialog;
    private ADA_TimesCard mCardAdapter;
    private LRecyclerView rvCardList;

    //优惠券
    private AlertDialog couponDialog;
    private RecyclerView rvCouponList;
    private ADA_CouponList mCouponAdapter;

    //优惠活动
    private AlertDialog activityDialog;
    private RecyclerView rvActivityList;
    private ADA_ActivityList mActivityAdapter;


    //抹零
    private AlertDialog eraseDialog;
    private EditText etErase;
    private PosKeyBoardView kbErase;

    //现金支付
    private AlertDialog cashPayDialog;
    private EditText etCash;
    private AlertDialog cashChangeDialog;
    private TextView tvRealPay;
    private TextView tvToPayAmount;
    private TextView tvChangeAmount;

    //余额支付
    private AlertDialog balancePayDialog;
    private EditText etBalance;
    private AlertDialog selectMemberAccountDialog;
    private PosKeyBoardView kbBalance;


    //微信支付宝支付
    private AlertDialog payDialog;
    private EditText etScanCode;
    private ImageView ivScanRemind;
    private ImageView ivPayType;
    private TextView tvPayType;
    private AlertDialog alipayChooseDialog;

    private AlertDialog sunMiPayErrorDialog;


    //银行卡支付
    private AlertDialog bankPosPayDialog;
    private StepView svProgress;
    private LoadingButton lbSendBankPay;
    private LoadingButton lbSettleDone;
    private LoadingButton lbRetryPay;

    //积分抵现
    private AlertDialog integralPayDialog;
    private EditText etIntegral;

    private AlertDialog bankDefaultPayDialog;
    private boolean isSelectShopPrice = false;

    private LedDisplayUtil ledDisplayUtil;

    // 引导气泡 -绑定、解绑会员，抹零权限
    private PopupWindow mMemberPopup;
    private PopupWindow mMlHintPopup;

    @Override
    protected void getBundleExtras(Bundle extras) {
        phone = extras.getString(SETTLE_MEMBER_PHONE, "");
        goodsJson = extras.getString(SETTLE_GOODS_JSON, "");
        ifGoodsSaved = extras.getBoolean(SETTLE_GOODS_IF_SAVED, false);
        orderType = extras.getString(SETTLE_ORDER_TYPE);
        settleType = StringUtils.get(SETTLE_ORDER_TYPE_GOODS.equals(extras.getString(SETTLE_ORDER_TYPE))
                ? SETTLE_SETTLE_TYPE_GOODS : SETTLE_ORDER_TYPE_TIMES_CARD.equals(extras.getString(SETTLE_ORDER_TYPE)) ? SETTLE_SETTLE_TYPE_TIMES_CARD : SETTLE_SETTLE_TYPE_SERVICE);

        mPresenter.initVariable(phone, goodsJson, orderType, settleType, ifGoodsSaved);

    }

    @Override
    protected void initEventAndData() {

        initView();

        //选择会员顾问
        initChooseServerDialog();

        // 初始化优惠券弹窗
        initCouponDialog();
        // 初始化次卡弹窗
        initCardDialog();
        //初始化活动弹窗
        initActivityDialog();
        // 初始化抹零弹窗
        initEraseDialog();
        //现金支付弹窗
        initCashPayDialog();
        //初始化找零弹窗
        initCashChangeDialog();
        //初始化会员余额支付弹窗
        initBalancePayDialog();
        //初始化会员账户选择弹窗
        initSelectMemberAccountDialog();

        // 初始化扫码支付弹窗
        initScanPayDialog();
        // 初始化商米支付失败弹窗
        initSunMiPayErrorDialog();
        //初始化支付宝支付方式选择弹窗
        initAlipayChooseDialog();
        //银行卡支付弹窗
        initBankDefaultPayDialog();
        // 初始化银行卡拉卡拉支付弹窗
        initBankPosPayDialog();

        //积分抵现弹窗
        initIntegralPayDialog();

        initSunMiReceiver();

        mPresenter.getMemberOrBillInfo();
        mPresenter.loadShopUserList();
        RxBus.getDefault().post(new RefreshMemberLevelEvent());


        ledDisplayUtil = new LedDisplayUtil(mContext);

    }

    private void initChooseServerDialog() {
        chooseServerDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_choose_server)
                .setDialogTitle("选择会员顾问")
                .setDialogNoConfirm()
                .setWidthAndHeight(438, 312)
                .create();

        rvServerList = chooseServerDialog.getView(R.id.server_list);
        chooseServerDialog.getView(R.id.tv_hint).setVisibility(View.GONE);
        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        rvServerList.setLayoutManager(manager);
        mServerAdapter = new ADA_DialogChooseServerList(mContext);
        rvServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_22)
                .setVertical(R.dimen.dp_20)
                .setColorResource(android.R.color.transparent)
                .build();
        rvServerList.addItemDecoration(divider);
        rvServerList.setHasFixedSize(true);
        rvServerList.setPullRefreshEnabled(false);
        rvServerList.setLoadMoreEnabled(false);

        ItemClickSupport.addTo(rvServerList).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                ServerEntity serverEntity = mServerAdapter.getData().get(position - 1);
                if (serverEntity.isChecked()) {
                    mServerAdapter.clearSelect();
                    serverEntity.setChecked(false);
                    mServerAdapter.setDefaultServerId("");
                    mPresenter.setSalesmanId("");
                    tvMemberWaiter.setText("请选择会员顾问");
                    closeDialog(chooseServerDialog);
                } else {
                    mServerAdapter.clearSelect();
                    serverEntity.setChecked(true);
                    mPresenter.setSalesmanId(serverEntity.getTechnicianId());
                    mServerAdapter.setDefaultServerId(serverEntity.getTechnicianId());
                    tvMemberWaiter.setText(StringUtils.get(serverEntity.getTechnicianName()));
                    closeDialog(chooseServerDialog);
                }
                mServerAdapter.notifyDataSetChanged();
            }
        });
    }


    private void initView() {
        MyFlexBoxLayoutManager layoutManager = new MyFlexBoxLayoutManager(mContext);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rvDiscountMenu.setLayoutManager(layoutManager);
        mDiscountMenuAdapter = new ADA_DiscountMenu(mContext);
        mDiscountMenuAdapter.setOnItemClickListener(new ADA_DiscountMenu.OnItemClickListener() {
            @Override
            public void onItemClick(int type) {
                switch (type) {
                    case DiscountMenuEntity.TYPE_TIME_CARD:
                        if (!mPresenter.isMlSelected()) {
                            if (ListUtil.isListEmpty(mCardAdapter.getDataList())) {
                                PosToast.INSTANCE.makeShortToast(mContext, "暂无可用次卡~");
                                return;
                            }
                            if (isUseCombinedPay()) {
                                PosToast.INSTANCE.makeShortToast(mContext, "支付方式已选择，不能使用优惠~");
                                return;
                            }
                            showDialog(cardDialog);
                        }
                        break;
                    case DiscountMenuEntity.TYPE_COUPON:
                        if (!mPresenter.isMlSelected()) {
                            if (ListUtil.isListEmpty(mCouponAdapter.getDataList())) {
                                PosToast.INSTANCE.makeShortToast(mContext, "暂无可用优惠券~");
                                return;
                            }
                            if (isUseCombinedPay()) {
                                PosToast.INSTANCE.makeShortToast(mContext, "支付方式已选择，不能使用优惠~");
                                return;
                            }
                            showDialog(couponDialog);
                        }
                        break;
                    case DiscountMenuEntity.TYPE_ACTIVITY:
                        if (!mPresenter.isMlSelected()) {
                            if (ListUtil.isListEmpty(mActivityAdapter.getDataList())) {
                                PosToast.INSTANCE.makeShortToast(mContext, "暂无可参与活动~");
                                return;
                            }
                            if (isUseCombinedPay()) {
                                PosToast.INSTANCE.makeShortToast(mContext, "支付方式已选择，不能使用优惠~");
                                return;
                            }
                            showDialog(activityDialog);
                        }
                        break;
                    case DiscountMenuEntity.TYPE_REDEEM:
                        if (!StringUtils.isTrue(AppConstants.TEMP_IS_REDEEM_GOODS)) {
                            PosToast.INSTANCE.makeShortToast(mContext, "未设置积分换购功能");
                            return;
                        }
                        if (mPresenter.isBindMember()) {
                            ACT_Redeem.startAcForResult(mContext, memberIntegral,
                                    mPresenter.getIntegralList(), REQUEST_CODE_REDEEM_GOODS);
                        }
                        break;
                }
            }
        });
        mDiscountMenuAdapter.setDataList(initMenu());
        rvDiscountMenu.setAdapter(mDiscountMenuAdapter);

        // 优惠活动列表适配器
        mDiscountAdapter = new ADA_DiscountList(mContext);
        mDiscountAdapter.setOnDeleteDiscountListener(new ADA_DiscountList.OnDeleteDiscountListener() {
            @Override
            public void onDeleteDiscount(final SettleCalculatePriceEntity.DiscountItemBean discountItemBean) {

                cancelDiscountDialog = new PosAlertDialog.Builder(mContext)
                        .setRemindText(String.format("确认要撤销【%s】吗？", discountItemBean.getName()))
                        .setPrimaryText("确认撤销")
                        .setPrimaryLoadingText("正在撤销")
                        .setUseLoadingButton(true)
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                RxBus.getDefault().post(new SettleDiscountEvent(discountItemBean));
                            }
                        }).build();
                cancelDiscountDialog.show();
            }
        });

        rvDiscountList.setLayoutManager(new LinearLayoutManager(mContext));
        rvDiscountList.setAdapter(mDiscountAdapter);
        rvDiscountList.setHasFixedSize(true);

        ivUnbindMember.setVisibility(SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.INVISIBLE : View.VISIBLE);


        rlCashPay.setVisibility(!AppUtil.isAppSunMiVersion() && SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.GONE : View.VISIBLE);
        rlBalancePay.setVisibility(SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.GONE : View.VISIBLE);
        rlCardPay.setVisibility(!AppUtil.isAppSunMiVersion() && SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.GONE : View.VISIBLE);
        rlIntegralPay.setVisibility(SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.GONE : View.VISIBLE);
        btnMl.setVisibility(!AppUtil.isAppSunMiVersion() && SETTLE_ORDER_TYPE_TIMES_CARD.equals(orderType) ? View.GONE : View.VISIBLE);

        rlCashPay.setClickable(false);
        rlBalancePay.setClickable(false);
        rlAliPay.setClickable(false);
        rlWxPay.setClickable(false);
        rlCardPay.setClickable(false);
        rlIntegralPay.setClickable(false);
        btnConfirmPay.setClickable(false);
    }

    private List<DiscountMenuEntity> initMenu() {
        ArrayList<DiscountMenuEntity> menuList = new ArrayList<>();

        if (!SETTLE_ORDER_TYPE_TIMES_CARD.equals(settleType)) {
            DiscountMenuEntity timeCardMenu = new DiscountMenuEntity();
            timeCardMenu.setIcon(R.drawable.svg_ic_menu_card);
            timeCardMenu.setTitle("次卡");
            timeCardMenu.setType(DiscountMenuEntity.TYPE_TIME_CARD);
            menuList.add(timeCardMenu);
        }

        DiscountMenuEntity couponMenu = new DiscountMenuEntity();
        couponMenu.setIcon(R.drawable.svg_ic_menu_coupon);
        couponMenu.setTitle("优惠券");
        couponMenu.setType(DiscountMenuEntity.TYPE_COUPON);
        menuList.add(couponMenu);

        if (!SETTLE_ORDER_TYPE_TIMES_CARD.equals(settleType)) {
            DiscountMenuEntity timeCardMenu = new DiscountMenuEntity();
            timeCardMenu.setIcon(R.drawable.svg_ic_menu_activity);
            timeCardMenu.setTitle("优惠活动");
            timeCardMenu.setType(DiscountMenuEntity.TYPE_ACTIVITY);
            menuList.add(timeCardMenu);
        }

        if (!SETTLE_ORDER_TYPE_TIMES_CARD.equals(settleType)) {
            DiscountMenuEntity timeCardMenu = new DiscountMenuEntity();
            timeCardMenu.setIcon(R.drawable.svg_ic_menu_redeem);
            timeCardMenu.setTitle("积分换购");
            timeCardMenu.setType(DiscountMenuEntity.TYPE_REDEEM);
            menuList.add(timeCardMenu);
        }
        return menuList;
    }


    private void initCouponDialog() {
        couponDialog = new PosDialog.PosBuilder(mContext, PosDialog.CONFIRM_TYPE_WITH_TEXT_SHADOW)
                .setRealDialogContent(R.layout.dialog_settle_coupon)
                .setDialogTitle("可用优惠券")
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        if (mPresenter.setTicket(mCouponAdapter.getSelectedItemList())) {
                            mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_COUPON,
                                    mCouponAdapter.getSelectedItemList().size());
                            mDiscountMenuAdapter.notifyDataSetChanged();
                            LoadingButton btnConfirm = couponDialog.getView(R.id.lb_confirm);
                            btnConfirm.startLoading("生成订单", rvCouponList, cardDialog.getView(R.id.iv_dialog_close));
                        }
                    }
                })
                .setWidthAndHeight(600, 571)
                .create();
        rvCouponList = couponDialog.getView(R.id.rv_coupons);
        rvCouponList.setLayoutManager(new LinearLayoutManager(mContext));
        mCouponAdapter = new ADA_CouponList(mContext);
        mCouponAdapter.setEnableSelected(true);
        rvCouponList.setAdapter(mCouponAdapter);
        couponDialog.toggleShowEmpty(true, R.id.cl_root);
        couponDialog.setText(R.id.tv_bottom_text, getFormatCountPrice("0", StringUtils.getFormattedMoneyWithUnit("0")));
        mCouponAdapter.setOnItemSelectedListener(new ADA_CouponList.OnItemSelectedListener() {
            @Override
            public void onItemSelected(TicketEntity item) {
                couponDialog.setText(R.id.tv_bottom_text, getFormatCountPrice(String.valueOf(mCouponAdapter.getSelectedItemList().size()),
                        StringUtils.getFormattedMoneyWithUnit(mPresenter.calculateCouponPrice(mCouponAdapter.getSelectedItemList()))));
            }
        });
    }

    private void initActivityDialog() {
        activityDialog = new PosDialog.PosBuilder(mContext, PosDialog.CONFIRM_TYPE_WITH_TEXT_SHADOW)
                .setRealDialogContent(R.layout.dialog_settle_coupon)
                .setDialogTitle("可用优惠活动")
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        if (mPresenter.setActivity(mActivityAdapter.getSelectedItemList())) {
                            mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_ACTIVITY, mActivityAdapter.getSelectedItemList().size());
                            mDiscountMenuAdapter.notifyDataSetChanged();
                            LoadingButton btnConfirm = activityDialog.getView(R.id.lb_confirm);
                            btnConfirm.startLoading("生成订单", rvCouponList, cardDialog.getView(R.id.iv_dialog_close));
                        }
                    }
                })
                .setWidthAndHeight(600, 571)
                .create();
        activityDialog.setText(R.id.tv_remind, "这里只显示本账单可用优惠活动哦~");
        rvActivityList = activityDialog.getView(R.id.rv_coupons);
        rvActivityList.setLayoutManager(new LinearLayoutManager(mContext));
        mActivityAdapter = new ADA_ActivityList(mContext);
        mActivityAdapter.setEnableSelected(true);
        mActivityAdapter.setDoubleCheck(true);
        rvActivityList.setAdapter(mActivityAdapter);
        activityDialog.toggleShowEmpty(true, R.id.cl_root);
        activityDialog.setText(R.id.tv_bottom_text, getFormatCountPrice("0", StringUtils.getFormattedMoneyWithUnit("0")));
        mActivityAdapter.setOnItemSelectedListener(new ADA_ActivityList.OnItemSelectedListener() {
            @Override
            public void onItemSelected(TicketEntity item) {
                activityDialog.setText(R.id.tv_bottom_text, getFormatCountPrice(String.valueOf(mActivityAdapter.getSelectedItemList().size()),
                        StringUtils.getFormattedMoneyWithUnit(mPresenter.calculateCouponPrice(mActivityAdapter.getSelectedItemList()))));
            }
        });
    }


    private void initCardDialog() {
        cardDialog = new PosDialog.PosBuilder(mContext, CONFIRM_TYPE_WITH_TEXT_SHADOW)
                .setRealDialogContent(R.layout.dialog_settle_time_card)
                .setSingleConfirmText("确定")
                .setDialogTitle("可用次卡")
                .setWidthAndHeight(400, 571)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        LoadingButton btnConfirm = cardDialog.getView(R.id.lb_confirm);
                        btnConfirm.startLoading("生成订单", rvCardList, cardDialog.getView(R.id.iv_dialog_close));
                        mPresenter.setMemberTimesCardId(mCardAdapter.getSelectedItemList());
                        mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_TIME_CARD,
                                mCardAdapter.getSelectedItemList().size());
                        mDiscountMenuAdapter.notifyDataSetChanged();
                    }
                })
                .create();
        cardDialog.setText(R.id.tv_bottom_text, getFormatCountPrice("0", StringUtils.getFormattedMoneyWithUnit("0")));
        rvCardList = cardDialog.getView(R.id.rv_cards);
        rvCardList.setLayoutManager(new LinearLayoutManager(mContext));
        mCardAdapter = new ADA_TimesCard(mContext);
        rvCardList.setAdapter(new LRecyclerViewAdapter(mCardAdapter));
        rvCardList.setPullRefreshEnabled(false);
        rvCardList.setLoadMoreEnabled(false);
        cardDialog.toggleShowEmpty(true, R.id.cl_root);

        mCardAdapter.setOnCountChangeListener(new ADA_TimesCard.OnCountChangeListener() {
            @Override
            public void onCountChange() {

                cardDialog.setText(R.id.tv_bottom_text, getFormatCountPrice(mPresenter.calculateSelectCardCount(mCardAdapter.getSelectedItemList()),
                        StringUtils.getFormattedMoneyWithUnit(mPresenter.calculateSelectCardPrice(mCardAdapter.getSelectedItemList()))));
            }
        });
    }

    public SpannableStringBuilder getFormatCountPrice(String selectCount, String price) {
        String targetText = String.format("总共选择 %s 张", selectCount);
        StringSpanUtils str = StringSpanUtils.init().addStr(targetText);
        str.setScaleWithKeyAndPosition(selectCount, 0, 1.25f);
        str.setForeColorWithKeyAndPosition(selectCount, 0, mContext.getResources().getColor(R.color.title_text_color));
        str.addStr(String.format("  立减 %s", price));
        str.setScaleWithKeyAndPosition(price, 1, 1.25f);
        str.setForeColorWithKeyAndPosition(price, 1, mContext.getResources().getColor(R.color.highlight_text_color));
        return str.build();
    }


    private void initEraseDialog() {
        eraseDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_erase)
                .setDialogTitle("抹零")
                .setDialogNoConfirm()
                .setWidthAndHeight(438, 467)
                .create();
        kbErase = eraseDialog.findViewById(R.id.kb_erase);
        etErase = eraseDialog.findViewById(R.id.et_erase);
        MoneyFormatUtil.setTextFilter(etErase);
        etErase.setFocusable(false);
        kbErase.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                String eraseMoney = etErase.getText().toString().trim();
                if (mPresenter.setMlAmount(eraseMoney)) {
                    etErase.setText("");
                    closeDialog(eraseDialog);
                }
            }
        });
    }

    private void initCashPayDialog() {
        cashPayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_cash_pay)
                .setUseRadiusBg(false)
                .setDialogNoConfirm()
                .setDialogTitle("现金支付")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        cashPayDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        etCash = cashPayDialog.getView(R.id.et_cash);
        etCash.setSelectAllOnFocus(true);
        PosKeyBoardView kbCash = cashPayDialog.getView(R.id.kb_cash);
        MoneyFormatUtil.setTextFilter(etCash);
        kbCash.attachTo(etCash, 999999.99, "");
        kbCash.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                if (IsFastClickUtil.isFastClick(etCash)) {
                    return;
                }
                mPresenter.settleOrderWithCash(etCash.getText().toString().trim());
            }
        });
    }

    private void initCashChangeDialog() {
        cashChangeDialog = new PosDialog.PosBuilder(mContext, PosDialog.CONFIRM_TYPE_SINGLE_CHOICE_SHADOW)
                .setRealDialogContent(R.layout.dialog_cash_change)
                .setUseRadiusBg(false)
                .setDialogTitle("现金找零")
                .setSingleConfirmText("完成")
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .setCancelableOntheOutside(false)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        LoadingButton lbConfirm = cashChangeDialog.getView(R.id.lb_confirm);
                        lbConfirm.startLoading("正在完成支付", cashChangeDialog.getView(R.id.iv_dialog_close));
                        String cashChange = StringUtils.getMoneyRemoveUnit(tvChangeAmount.getText().toString().trim());
                        String cashInput = StringUtils.getMoneyRemoveUnit(tvRealPay.getText().toString().trim());
                        mPresenter.settleOrderWithCashChange(cashChange, cashInput);
                    }
                })
                .create();

        tvRealPay = cashChangeDialog.getView(R.id.tv_real_pay);
        tvToPayAmount = cashChangeDialog.getView(R.id.tv_to_pay_amount);
        tvChangeAmount = cashChangeDialog.getView(R.id.tv_change_amount);

    }


    private void initBalancePayDialog() {
        balancePayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_balance_pay)
                .setUseRadiusBg(false)
                .setDialogTitle("余额支付")
                .setSingleConfirmText("立即支付")
                .setDialogNoConfirm()
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        balancePayDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        balancePayDialog.getView(R.id.lb_confirm);
        etBalance = balancePayDialog.getView(R.id.et_balance);
        etBalance.setSelectAllOnFocus(true);
        kbBalance = balancePayDialog.getView(R.id.kb_balance);
        MoneyFormatUtil.setTextFilter(etBalance);
        kbBalance.attachTo(etBalance, 999999.99, "");
        kbBalance.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                if (IsFastClickUtil.isFastClick(etBalance)) {
                    return;
                }
                mPresenter.settleOrderWithMemberBalance(etBalance.getText().toString().trim(), isSelectShopPrice);
            }
        });

        View.OnClickListener goSelectAccount = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                closeDialog(balancePayDialog);
                showDialog(selectMemberAccountDialog);
            }
        };
        balancePayDialog.setOnClickListener(R.id.tv_balance, goSelectAccount);
        balancePayDialog.setOnClickListener(R.id.iv_go_right, goSelectAccount);


    }

    private void initSelectMemberAccountDialog() {
        selectMemberAccountDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_select_member_account)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(selectMemberAccountDialog);
                        showDialog(balancePayDialog);
                    }
                })
                .setDialogNoConfirm()
                .setDialogTitle("选择支付账户")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();

        View.OnClickListener onAccountSelect = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.rl_shop:
                        if (!mPresenter.isSelectSameAccount(true)) {
                            showError("门店账户和公司账户不能同时使用");
                            return;
                        }
                        isSelectShopPrice = true;
                        balancePayDialog.setText(R.id.tv_balance_title, "门店账户余额");
                        balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit
                                (mPresenter.getMemberAccount() != null ?
                                        mPresenter.getMemberAccount().getShopPrice() : "0"));
                        showShopAccountChecked(true);
                        break;
                    case R.id.rl_company:

                        if (!mPresenter.isSelectSameAccount(false)) {
                            showError("门店账户和公司账户不能同时使用");
                            return;
                        }
                        isSelectShopPrice = false;
                        balancePayDialog.setText(R.id.tv_balance_title, "连锁公司账户余额");
                        balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit
                                (mPresenter.getMemberAccount() != null ?
                                        mPresenter.getMemberAccount().getCompanyPrice() : "0"));
                        showShopAccountChecked(false);
                        break;
                }
                closeDialog(selectMemberAccountDialog);
                showDialog(balancePayDialog);
            }
        };
        selectMemberAccountDialog.setOnClickListener(R.id.rl_company, onAccountSelect);
        selectMemberAccountDialog.setOnClickListener(R.id.rl_shop, onAccountSelect);
        showShopAccountChecked(true);
    }

    private void showShopAccountChecked(boolean isShopAccount) {
        CheckBox cbShop = selectMemberAccountDialog.getView(R.id.cb_shop_check);
        CheckBox cbCompany = selectMemberAccountDialog.getView(R.id.cb_company_check);
        cbShop.setChecked(isShopAccount);
        cbCompany.setChecked(!isShopAccount);
    }


    /**
     * 初始化扫码弹窗
     */
    private void initScanPayDialog() {

        payDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_scan_gun_hint)
                .setUseRadiusBg(false)
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        etScanCode = payDialog.getView(R.id.et_scan_code);
        ivScanRemind = payDialog.getView(R.id.iv_scan_remind);
        etScanCode.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(this, etScanCode);
        // 监听扫码输入完成的监听
        etScanCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.ACTION_DOWN) {
                    String code = etScanCode.getText().toString().trim();
                    // 下传到 P 层处理逻辑
                    mPresenter.executeScanCode(code);
                }
                return true;
            }
        });
        payDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        ivPayType = payDialog.getView(R.id.iv_pay_type);
        tvPayType = payDialog.getView(R.id.tv_pay_type);
        TextView tvScanRemind = payDialog.getView(R.id.tv_scan_remind);
        SpannableStringBuilder remindStr = StringSpanUtils.init()
                .addForegroundColorHighLightWithKey(getResources().getColor(R.color.order_status_service), "请使用扫码枪扫描顾客二维码...", "扫码枪")
                .setForeColorWithKeyAndPosition("二维码", 0, getResources().getColor(R.color.order_status_service)).build();
        tvScanRemind.setText(remindStr);

    }

    private void initSunMiPayErrorDialog() {
        sunMiPayErrorDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_sunmi_pay_error)
                .setUseRadiusBg(false)
                .setDialogTitle("微信支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        ImageView ivClose = sunMiPayErrorDialog.getView(R.id.iv_dialog_close);
        ivClose.setVisibility(View.GONE);
        sunMiPayErrorDialog.setOnClickListener(R.id.lb_refresh, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
                lbConfirm.startLoading("正在刷新");
                mPresenter.querySmPayOrderInfo(false);
            }
        });

    }


    private void initAlipayChooseDialog() {
        alipayChooseDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_alipay_choose)
                .setUseRadiusBg(false)
                .setDialogTitle("支付宝支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        alipayChooseDialog.setOnClickListener(R.id.tv_alipay_scan, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showPayDialogByStatus(true, true, true);
                closeDialog(alipayChooseDialog);
            }
        });

        alipayChooseDialog.setOnClickListener(R.id.tv_alipay_face, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.executeFacePay();
                closeDialog(alipayChooseDialog);
                ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
                ivClose.setVisibility(View.GONE);
            }
        });
    }


    private void initBankDefaultPayDialog() {
        bankDefaultPayDialog = new PosDialog.PosBuilder(mContext, PosDialog.CONFIRM_TYPE_SINGLE_CHOICE_SHADOW)
                .setRealDialogContent(R.layout.dialog_bank_pay)
                .setUseRadiusBg(false)
                .setDialogTitle("银行卡支付")
                .setSingleConfirmText("已支付成功")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        LoadingButton loadingButton = bankDefaultPayDialog.getView(R.id.lb_confirm);
                        loadingButton.startLoading("正在完成", bankDefaultPayDialog.getView(R.id.iv_dialog_close));
                        mPresenter.settleOrderWithBank();
                    }
                })
                .create();
    }

    private void initBankPosPayDialog() {
        bankPosPayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_bank_pos_pay)
                .setUseRadiusBg(false)
                .setDialogTitle("银行卡支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        svProgress = bankPosPayDialog.getView(R.id.sv_progress);
        svProgress.setProgressText("发送账单至POS", "POS刷卡", "结账成功");
        lbSendBankPay = bankPosPayDialog.getView(R.id.lb_bank_confirm);
        lbSettleDone = bankPosPayDialog.getView(R.id.lb_settle_done);
        lbRetryPay = bankPosPayDialog.getView(R.id.lb_retry);

        bankPosPayDialog.setOnClickListener(R.id.lb_bank_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbSendBankPay.startLoading("正在发送", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.settleOrderWithBank();
            }
        });
        bankPosPayDialog.setOnClickListener(R.id.lb_settle_done, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbSettleDone.startLoading("正在完成", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.requestOrderInfoAfterTimeOut();
            }
        });
        bankPosPayDialog.setOnClickListener(R.id.lb_retry, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbRetryPay.startLoading("正在发送", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.settleOrderWithBank();
            }
        });
    }

    private void initIntegralPayDialog() {
        integralPayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_integral_pay)
                .setUseRadiusBg(false)
                .setDialogNoConfirm()
                .setDialogTitle("积分抵现")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        integralPayDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        etIntegral = integralPayDialog.getView(R.id.et_integral);
        etIntegral.setSelectAllOnFocus(true);
        PosKeyBoardView kbCash = integralPayDialog.getView(R.id.kb_cash);
        MoneyFormatUtil.setTextFilter(etIntegral);
        kbCash.attachTo(etIntegral, 999999.99, "");
        kbCash.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                if (IsFastClickUtil.isFastClick(etIntegral)) {
                    return;
                }
                mPresenter.settleOrderWithIntegral(etIntegral.getText().toString().trim());
            }
        });
    }

    private void initSunMiReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SUNMI_PAY_ACTION);
        registerReceiver(receiver, filter);
    }

    @Override
    public void setMemberInfo(MemberEntity memberEntity) {

        if (memberEntity == null) {
            // 解绑会员时，会回调 null 回来，隐藏会员信息
            rlMemberUnBind.setVisibility(View.VISIBLE);
            rlMemberBind.setVisibility(View.GONE);
            memberIntegral = "";
        }
//
        if (memberEntity != null) {
            // 设置显示会员信息，隐藏登录信息
            rlMemberUnBind.setVisibility(View.GONE);
            rlMemberBind.setVisibility(View.VISIBLE);
            // 设置基本会员信息
            tvMemberName.setText(StringUtils.isEmpty(memberEntity.getName()) ? "暂无姓名" : StringUtils.getString(memberEntity.getName()));
            tvMemberPhone.setText(StringUtils.getString(memberEntity.getPhone()));
            tvMemberBalance.setText(StringUtils.getFormattedMoneyWithUnit(memberEntity.getCurrentAmount()));
            tvMemberPoints.setText(StringUtils.getString(memberEntity.getMemberPoints()));
            memberIntegral = memberEntity.getMemberPoints();
            integralPayDialog.setText(R.id.tv_integral_use, BigDecimalUtil.getNumber(memberEntity.getMemberPoints()));
            integralPayDialog.setText(R.id.tv_integral_info, String.format("%s积分=1元", BigDecimalUtil.getNumber(memberEntity.getHowMoneyOne())));

            if (!StringUtils.isEmpty(memberEntity.getBirthday()) && AppDateUtil.isBirthdayDay(new Date(),
                    AppDateUtil.timeStamp2Date(memberEntity.getBirthday()))) {
                tvBirthday.setVisibility(View.VISIBLE);
            } else {
                tvBirthday.setVisibility(View.GONE);
            }
        } else {
            tvBirthday.setVisibility(View.GONE);
        }

    }

    @Override
    public void showSearchMemberSuccess() {
        RxBus.getDefault().post(new BindMemberEntity());
    }

    @Override
    public void showAddMemberSuccess() {
        PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功~", false);
    }

    @Override
    public void showServerList(List<ServerEntity> servers) {

        if (!ListUtil.isListEmpty(servers)) {

            chooseServerDialog.toggleShowEmpty(false, R.id.root_view);
            mServerAdapter.setData(servers);
            rvServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));

            // 根据数据集大小设置弹窗高度
            // 默认高度 300，如果超过 8 条数据，高度就高一点
            if (servers.size() > 4) {
                ViewGroup.LayoutParams params = rvServerList.getLayoutParams();
                params.height = Math.min(DisplayUtil.dip2px(mContext, 260), params.height *= 1.3);
                rvServerList.setLayoutParams(params);
            }
        } else {
            chooseServerDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "暂无会员导购~");
        }
    }

    @Override
    public void showTimeChanged(long time) {
        payDialog.setText(R.id.tv_pay_remind_time, String.format("正在等待顾客支付密码 (%sS)", time));
    }

    @Override
    public void showAddedPay() {
        closeDialog(cashPayDialog, balancePayDialog, integralPayDialog);
    }

    @Override
    public void showMemberAccountInfo(String companyPrice, String shopPrice) {

        if ((LoginEntity.STORE_TYPE_COMPANY == AppConstants.TEMP_SHOP_STORE_TYPE
                && !StringUtils.isMoreThenZero(shopPrice))) {
            TextView tvBalance = balancePayDialog.getView(R.id.tv_balance);
            tvBalance.setClickable(false);
            balancePayDialog.getView(R.id.iv_go_right).setVisibility(View.INVISIBLE);

            balancePayDialog.setText(R.id.tv_balance_title, "账户余额");
            isSelectShopPrice = false;
            balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit(companyPrice));

        } else if ((LoginEntity.STORE_TYPE_SHOP == AppConstants.TEMP_SHOP_STORE_TYPE
                || LoginEntity.STORE_TYPE_DEPOSIT == AppConstants.TEMP_SHOP_STORE_TYPE)
                && !StringUtils.isMoreThenZero(companyPrice)) {
            TextView tvBalance = balancePayDialog.getView(R.id.tv_balance);
            tvBalance.setClickable(false);
            balancePayDialog.getView(R.id.iv_go_right).setVisibility(View.INVISIBLE);
            balancePayDialog.setText(R.id.tv_balance_title, "账户余额");
            isSelectShopPrice = true;
            balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit(shopPrice));

        } else {
            TextView tvBalance = balancePayDialog.getView(R.id.tv_balance);
            tvBalance.setClickable(true);
            balancePayDialog.getView(R.id.iv_go_right).setVisibility(View.VISIBLE);

            if (LoginEntity.STORE_TYPE_COMPANY == AppConstants.TEMP_SHOP_STORE_TYPE) {
                balancePayDialog.setText(R.id.tv_balance_title, "连锁公司账户余额");
                isSelectShopPrice = false;
                balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit(companyPrice));
            } else {
                isSelectShopPrice = true;
                balancePayDialog.setText(R.id.tv_balance_title, "门店账户余额");
                balancePayDialog.setText(R.id.tv_balance, StringUtils.getFormattedMoneyWithUnit(shopPrice));
            }
        }

        selectMemberAccountDialog.setText(R.id.tv_shop_amount, StringUtils.getFormattedMoneyWithUnit(shopPrice));
        selectMemberAccountDialog.setText(R.id.tv_company_amount, StringUtils.getFormattedMoneyWithUnit(companyPrice));
        showShopAccountChecked(isSelectShopPrice);
    }

    @Override
    public void showRefreshDone() {
        if (isUnbindMember && unBindMemberDialog != null) {
            unBindMemberDialog.cancelLoading();
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已解绑");
            isUnbindMember = false;
        }

        showPopupHint();
    }

    @Override
    public void showRedeemGoodsChange(List<GoodsEntity> integralList) {
        mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_REDEEM, integralList.size());
        mDiscountMenuAdapter.notifyDataSetChanged();
    }

    @Override
    public void showSunMiPayNetError() {
        if (sunMiPayErrorDialog != null && sunMiPayErrorDialog.isShowing()) {
            LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
            lbConfirm.stopLoading("刷新试试");
        }
        showError("网络连接失败");
        closeDialog(payDialog);
        showDialog(sunMiPayErrorDialog);
    }

    @Override
    public void setDiscountAreaInfo(SettleDiscountAreaEntity discountAreaEntity) {

        cardDialog.toggleShowEmpty(ListUtil.isListEmpty(discountAreaEntity.getMemberCardList()), R.id.cl_root);
        mCardAdapter.update(discountAreaEntity.getMemberCardList(), true);

        mDiscountMenuAdapter.updateUseCountByType(DiscountMenuEntity.TYPE_TIME_CARD, discountAreaEntity.getMemberCardSize());
        mDiscountMenuAdapter.updateUseCountByType(DiscountMenuEntity.TYPE_COUPON, discountAreaEntity.getMemberTicketSize());
        mDiscountMenuAdapter.updateUseCountByType(DiscountMenuEntity.TYPE_ACTIVITY, discountAreaEntity.getMarketActivitySize());
        mDiscountMenuAdapter.updateUseCountByType(DiscountMenuEntity.TYPE_REDEEM, Integer.parseInt(BigDecimalUtil.getNumber(discountAreaEntity.getIntegralGoods())));
        mDiscountMenuAdapter.notifyDataSetChanged();

        couponDialog.toggleShowEmpty(ListUtil.isListEmpty(discountAreaEntity.getMemberTicket()), R.id.cl_root);
        mCouponAdapter.update(discountAreaEntity.getMemberTicket(), true);

        activityDialog.toggleShowEmpty(ListUtil.isListEmpty(discountAreaEntity.getMarketActivityList()), R.id.cl_root);
        mActivityAdapter.update(discountAreaEntity.getMarketActivityList(), true);

    }


    @Override
    public void setSettleInfo(SettleCalculatePriceEntity entity) {

        // 设置页面数据金额显示
        tvOriginAmount.setText(StringUtils.getFormattedMoneyWithUnit(entity.getTotalAmount()));

        tvBargain.setText(StringUtils.getFormattedMoneyWithUnit(entity.getBargainDiscount()));

        tvGoodsDiscount.setText(StringUtils.getFormattedMoneyWithUnit(entity.getGoodsDiscount()));
        rlGoodsDiscount.setVisibility(StringUtils.isEmpty(entity.getGoodsDiscount()) ? View.GONE : View.VISIBLE);

        tvMemberDiscount.setText(StringUtils.getFormattedMoneyWithUnit(entity.getMemberDiscount()));

        rlPresent.setVisibility(!StringUtils.isEmpty(entity.getPresentDiscount()) &&
                StringUtils.isMoreThenZero(entity.getPresentDiscount()) ? View.VISIBLE : View.GONE);
        tvPresent.setText(StringUtils.getFormattedMoneyWithUnit(entity.getPresentDiscount()));

        tvResultAmount.setText(StringUtils.getFormattedMoneyWithUnit(entity.getToPayAmount()));
        btnConfirmPay.setEnabled(!StringUtils.isMoreThenZero(entity.getToPayAmount()));
        ledDisplayUtil.displayTotal(entity.getToPayAmount());

        // 设置折扣列表
        mDiscountAdapter.update(entity.getDiscountItem(), true);

        closeDiscountLoadingButton(true);

        rlCashPay.setClickable(true);
        rlBalancePay.setClickable(true);
        rlAliPay.setClickable(true);
        rlWxPay.setClickable(true);
        rlCardPay.setClickable(true);
        rlIntegralPay.setClickable(true);
        btnConfirmPay.setClickable(true);

    }

    private void closeDiscountLoadingButton(boolean success) {
        if (cardDialog != null && cardDialog.isShowing()) {
            LoadingButton btnConfirm = cardDialog.getView(R.id.lb_confirm);
            btnConfirm.stopLoading("确定");
            if (success) {
                cardDialog.dismiss();
            }
        }
        if (couponDialog != null && couponDialog.isShowing()) {
            LoadingButton btnConfirm = couponDialog.getView(R.id.lb_confirm);
            btnConfirm.stopLoading("确定");
            if (success) {
                couponDialog.dismiss();
            }
        }
        if (activityDialog != null && activityDialog.isShowing()) {
            LoadingButton btnConfirm = activityDialog.getView(R.id.lb_confirm);
            btnConfirm.stopLoading("确定");
            if (success) {
                activityDialog.dismiss();
            }
        }
        if (cancelDiscountDialog != null && cancelDiscountDialog.isShowing()) {
            cancelDiscountDialog.cancelLoading();
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已撤销");
        }

    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        closeDiscountLoadingButton(false);
    }

    @Override
    public void showCashChangeDialog(String cashChange, String cashInput) {

        tvRealPay.setText(StringUtils.getFormattedMoneyWithUnit(cashInput));
        tvToPayAmount.setText(StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
        tvChangeAmount.setText(StringUtils.getFormattedMoneyWithUnit(String.valueOf(cashChange)));
        closeDialog(cashPayDialog);
        showDialog(cashChangeDialog);
    }

    @Override
    public void openDrawer() {
        PrinterService.openDrawer(mContext);
    }

    @Override
    public void resetScanCodeStatus() {
        etScanCode.setText("");
    }


    @Override
    public void showCouponSelectedChange(int discountType, List<TicketEntity> ticketList) {
        if (discountType == TYPE_COUPON) {
            mCouponAdapter.setSelectedItemList(ticketList);
            mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_COUPON, mCouponAdapter.getSelectedItemList().size());
            mDiscountMenuAdapter.notifyDataSetChanged();
            couponDialog.setText(R.id.tv_bottom_text, getFormatCountPrice(String.valueOf(mCouponAdapter.getSelectedItemList().size()),
                    StringUtils.getFormattedMoneyWithUnit(mPresenter.calculateCouponPrice(mCouponAdapter.getSelectedItemList()))));
        } else if (discountType == TYPE_ACTIVITY) {
            mActivityAdapter.setSelectedItemList(ticketList);
            mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_ACTIVITY, mActivityAdapter.getSelectedItemList().size());
            mDiscountMenuAdapter.notifyDataSetChanged();
            activityDialog.setText(R.id.tv_bottom_text, getFormatCountPrice(String.valueOf(mActivityAdapter.getSelectedItemList().size()),
                    StringUtils.getFormattedMoneyWithUnit(mPresenter.calculateCouponPrice(mActivityAdapter.getSelectedItemList()))));
        }
    }

    @Override
    public void showTimeCardSelectedChange(List<TimeCardEntity> timesCards) {
        mCardAdapter.setSelectedItemList(timesCards);
        rvCardList.setAdapter(new LRecyclerViewAdapter(mCardAdapter));
        mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_TIME_CARD, mCardAdapter.getSelectedItemList().size());
        mDiscountMenuAdapter.notifyDataSetChanged();
    }


    @Override
    public void onSettleSuccess() {

        // 关闭支付弹窗
        closeDialog(payDialog, bankPosPayDialog, balancePayDialog, sunMiPayErrorDialog);

        closeSettleLoadingButton();

        PosToast.INSTANCE.makeSuccessToast(mContext, "支付成功");
        ledDisplayUtil.clear();

        RxBus.getDefault().post(new SettleSuccessEvent());
    }

    private void closeSettleLoadingButton() {

        if (bankDefaultPayDialog != null && bankDefaultPayDialog.isShowing()) {
            LoadingButton loadingButton = bankDefaultPayDialog.getView(R.id.lb_confirm);
            loadingButton.stopLoading("已完成支付");

        }

        if (bankPosPayDialog != null && bankPosPayDialog.isShowing()) {
            lbSendBankPay.stopLoading("立即发送");
            lbSettleDone.stopLoading("已支付成功");
            lbRetryPay.stopLoading("重新发送账单");
        }

        if (cashChangeDialog != null && cashChangeDialog.isShowing()) {
            LoadingButton lbConfirm = cashChangeDialog.getView(R.id.lb_confirm);
            lbConfirm.stopLoading("完成");
        }

        if (sunMiPayErrorDialog != null && sunMiPayErrorDialog.isShowing()) {
            LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
            lbConfirm.stopLoading("刷新试试");
        }

        btnConfirmPay.setText("结账");

    }

    @Override
    public void showSettleError(int code, String msg) {

        closeSettleLoadingButton();

        // 根据 code 判断当前是否是超时，超时展示弹窗，否则 toast 提示错误
        switch (code) {
            case SettleAccountPresenter.CODE_BANK_TIME_OUT:
                showBankPayByStatus(true, false);
                break;
            case SettleAccountPresenter.CODE_SUN_MI_TIME_OUT:
            case SettleAccountPresenter.CODE_SUN_MI_NET_ERROR:
                closeDialog(payDialog);
                showDialog(sunMiPayErrorDialog);
                break;
            case SettleAccountPresenter.CODE_INVENTORY_ERROR:
                List<GoodsEntity> goodsEntities = JSON.parseArray(msg, GoodsEntity.class);
                StringBuilder builder = new StringBuilder();
                for (int index = 0; index < goodsEntities.size(); index++) {
                    GoodsEntity goodsEntity = goodsEntities.get(index);
                    builder.append(goodsEntity.getGoodsName());
                    if (index < goodsEntities.size() - 1) {
                        builder.append("\n");
                    }
                }
                GoodsUtil.showCheckGoodsInventoryResultDialog(mContext, "以下商品正在盘点，无法售卖", builder.toString());
                break;
            default:
                // 关闭支付相关的弹窗
                closeDialog(payDialog, bankPosPayDialog, sunMiPayErrorDialog);
                showError(msg);
                break;
        }
    }

    @Override
    public void showGetBillError() {

        finish();
    }


    @Override
    public void showPayDialog(String payType) {
        switch (payType) {
            case BillUtil.PAY_TYPE_BALANCE:

                // 弹出会员余额支付的弹窗
                balancePayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
                kbBalance.attachTo(etBalance, Double.parseDouble(mPresenter.getToPayAmount()), String.format("最大支付金额为：%s元", mPresenter.getToPayAmount()));
                showDialog(balancePayDialog);

                String displayPrice = "0";
                String balancePrice = isSelectShopPrice ? BigDecimalUtil.getNumber(mPresenter.getMemberAccount().getShopPrice()) :
                        StringUtils.get(mPresenter.getMemberAccount().getCompanyPrice());
                if (BigDecimalUtil.compareTo(mPresenter.getToPayAmount(), balancePrice) == -1) {
                    displayPrice = mPresenter.getToPayAmount();
                } else {
                    displayPrice = balancePrice;
                }
                etBalance.requestFocus();
                etBalance.setText(StringUtils.getFormattedMoney(displayPrice));
                etBalance.selectAll();
                break;

            case BillUtil.PAY_TYPE_ALI:
                if (AppUtil.isAppSunMiVersion() && AppUtil.isFacePayPos()) {
                    showDialog(alipayChooseDialog);
                } else {
                    showPayDialogByStatus(true, true, false);
                }
                break;
            case BillUtil.PAY_TYPE_WE_CHAT:
                showPayDialogByStatus(false, true, false);
                break;
            case BillUtil.PAY_TYPE_BANK_POS:
                showBankPayByStatus(false, true);
                break;
            case BillUtil.PAY_TYPE_BANK:
                bankDefaultPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
                showDialog(bankDefaultPayDialog);
                break;
            case BillUtil.PAY_TYPE_INTEGRAL:
                showDialog(integralPayDialog);
                etIntegral.setText("");
                integralPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
                break;
        }
    }

    private void showBankPayByStatus(boolean isTimeOut, boolean isFirst) {
        bankPosPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
        if (isTimeOut) {
            bankPosPayDialog.getView(R.id.group_progress).setVisibility(View.GONE);
            bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.GONE);
            bankPosPayDialog.getView(R.id.group_time_out).setVisibility(View.VISIBLE);
        } else {
            bankPosPayDialog.getView(R.id.group_progress).setVisibility(View.VISIBLE);
            bankPosPayDialog.getView(R.id.group_time_out).setVisibility(View.GONE);
            ImageView ivProgress = bankPosPayDialog.getView(R.id.iv_progress);
            if (isFirst) {
                svProgress.setCurrentPosition(0);
                bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.VISIBLE);
                bankPosPayDialog.setText(R.id.tv_progress, "第一步，发送账单至POS");
                bankPosPayDialog.setText(R.id.tv_progress_remind, "请保证pos网络连接顺畅！");
                ivProgress.setImageResource(R.drawable.svg_ic_bank_pay_send);
            } else {
                svProgress.setCurrentPosition(1);
                ivProgress.setImageResource(R.drawable.svg_ic_bank_pay_waiting);
                bankPosPayDialog.setText(R.id.tv_progress, "第二步，使用拉卡拉pos刷卡支付 (60s)");
                bankPosPayDialog.setText(R.id.tv_progress_remind, "未收到账单？请保证pos网络顺畅！");
                bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.GONE);

            }
        }

        showDialog(bankPosPayDialog);
    }

    private void showPayDialogByStatus(boolean isAlipay, boolean isScan, boolean isShowBack) {
        payDialog.setText(R.id.tv_dialog_title, isAlipay ? "支付宝支付" : "微信支付");
        payDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
        sunMiPayErrorDialog.setText(R.id.tv_pay_type, isAlipay ? "支付宝支付" : "微信支付");
        sunMiPayErrorDialog.setText(R.id.tv_dialog_title, isAlipay ? "支付宝支付" : "微信支付");
        sunMiPayErrorDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
        ImageView ivSunMIPayType = sunMiPayErrorDialog.getView(R.id.iv_pay_type);
        ivSunMIPayType.setImageResource(isAlipay ? R.drawable.svg_ic_pay_dialog_alipay : R.drawable.svg_ic_pay_dialog_wxpay);
        if (isScan) {
            ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
            ivClose.setVisibility(View.VISIBLE);
            etScanCode.setVisibility(View.VISIBLE);
            etScanCode.requestFocus();
            tvPayType.setText(isAlipay ? "支付宝支付" : "微信支付");
            ivPayType.setImageResource(isAlipay ? R.drawable.svg_ic_pay_dialog_alipay : R.drawable.svg_ic_pay_dialog_wxpay);
        } else {
            etScanCode.setVisibility(View.GONE);
            ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
            ivClose.setVisibility(View.GONE);
        }

        if (isShowBack) {
            ImageView ivBack = payDialog.getView(R.id.iv_dialog_back);
            ivBack.setVisibility(View.VISIBLE);
            payDialog.setText(R.id.tv_dialog_title, "支付宝扫码支付");
            ivBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closeDialog(payDialog);
                    showDialog(alipayChooseDialog);
                }
            });
        } else {
            ImageView ivBack = payDialog.getView(R.id.iv_dialog_back);
            ivBack.setVisibility(View.GONE);
        }

        ivScanRemind.setImageResource(isScan ? R.drawable.svg_ic_pay_dialog_scan_remind : R.drawable.svg_ic_pay_waitting);
        ivPayType.setVisibility(isScan ? View.VISIBLE : View.INVISIBLE);
        tvPayType.setVisibility(isScan ? View.VISIBLE : View.INVISIBLE);

        payDialog.getView(R.id.tv_scan_remind).setVisibility(isScan ? View.VISIBLE : View.GONE);
        payDialog.getView(R.id.tv_pay_remind).setVisibility(isScan ? View.GONE : View.VISIBLE);
        payDialog.getView(R.id.tv_pay_remind_time).setVisibility(isScan ? View.GONE : View.VISIBLE);
        etScanCode.requestFocus();
        showDialog(payDialog);
    }

    @Override
    public void showWaitingDialog(boolean isAlipay) {

        showPayDialogByStatus(isAlipay, false, false);
    }

    @Override
    public void showBankWaitingDialog() {
        showBankPayByStatus(false, false);
    }

    @Override
    public void showEraseDialog(double ceilingAmount) {
        kbErase.attachTo(etErase, ceilingAmount, String.format("最大抹零金额为：%s元", ceilingAmount));
        eraseDialog.setText(R.id.tv_erase_price, StringUtils.getFormattedMoneyWithUnit(String.valueOf(ceilingAmount)));
        showDialog(eraseDialog);
    }

    @Override
    public void clearCouponCheck(int ticketType) {
        switch (ticketType) {
            case TYPE_COUPON:
                mCouponAdapter.clearCheckStatus();
                closeDialog(couponDialog);
                break;
            case TYPE_TIMES_CARD:
                mCardAdapter.clearCheckStatus();
                closeDialog(cardDialog);
                break;
        }
    }

    @Override
    public void doPrintAfterSettleSuccess(BillDetailEntity billDetailEntity) {

        PrintEntity printEntity = BillUtil.generatePrintEntity(billDetailEntity);

        // 发送广播执行打印
        if (printEntity != null) {
            PrinterService.doPrintTicket(mContext, printEntity, AppConstants.CONFIG_PRINT_COUNT);
        }

        finish();

    }


    @OnClick({R.id.rl_cash_pay_bg, R.id.rl_balance_pay_bg, R.id.rl_ali_pay_bg, R.id.rl_card_pay_bg, R.id.rl_wx_pay_bg,
            R.id.rl_member_unbind, R.id.iv_member_link, R.id.rl_server_bg, R.id.rl_integral_pay_bg,
            R.id.iv_add_member, R.id.btn_ml, R.id.btn_settle, R.id.iv_back})
    public void onClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_member_unbind:
                AddMemberUtil.showSelectMemberDialog(mContext, mPresenter);
//                showDialog(selectMemberDialog);
//                etSelectPhone.setText("");
                break;
            case R.id.iv_member_link:
                PopupUtil.dismissPopup(PopupUtil.SETTLE_UNBIND_MEMBER, mMemberPopup);
                isUnbindMember = true;
                AddMemberUtil.doSthAboutMemberBinding(mContext, false, mPresenter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        unBindMemberDialog = (PosAlertDialog) dialog;
                        mCardAdapter.clearCheckStatus();
                        mPresenter.resetMemberStatusAndRefresh();
                    }
                });
                break;
            case R.id.iv_add_member:
                PopupUtil.dismissPopup(PopupUtil.SETTLE_ADD_MEMBER, mMemberPopup);
                AddMemberUtil.doSthAboutMemberBinding(mContext, true, mPresenter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mCardAdapter.clearCheckStatus();
                        mPresenter.resetMemberStatusAndRefresh();
                    }
                });
                break;
            case R.id.rl_server_bg:
                showDialog(chooseServerDialog);
                mServerAdapter.setDefaultServerId(mPresenter.getSalesmanId());
                rvServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));
                break;

            case R.id.btn_ml:
                PopupUtil.dismissPopup(PopupUtil.SETTLE_ERASE_ZERO, mMlHintPopup);
                mPresenter.getMaxValueForEraseDialog();
                break;

            case R.id.rl_cash_pay_bg:
                showDialog(cashPayDialog);
                cashPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(mPresenter.getToPayAmount()));
                etCash.requestFocus();
                etCash.setText(StringUtils.getFormattedMoney(mPresenter.getToPayAmount()));
                etCash.selectAll();
                break;
            case R.id.rl_balance_pay_bg:
                mPresenter.settleOrderWithMemberBalance();
                break;
            case R.id.rl_integral_pay_bg:
                if (!StringUtils.isTrue(AppConstants.TEMP_IS_INTEGRAL_DISCOUNT)) {
                    PosToast.INSTANCE.makeShortToast(mContext, "未配置积分抵现功能");
                    return;
                }
                mPresenter.settleOrderWithMemberIntegral();
                break;
            case R.id.rl_ali_pay_bg:
                mPresenter.settleOrderOnline(BillUtil.PAY_TYPE_ALI);
                break;
            case R.id.rl_wx_pay_bg:
                mPresenter.settleOrderOnline(BillUtil.PAY_TYPE_WE_CHAT);
                break;
            case R.id.rl_card_pay_bg:
                mPresenter.settleOrderOnline(BillUtil.PAY_TYPE_BANK);
                break;
            case R.id.btn_settle:
                btnConfirmPay.startLoading("正在完成");
                mPresenter.settleOrderWithCash("0");
                break;

        }
    }

    private boolean isUseCombinedPay() {
        if (!ListUtil.isListEmpty(mDiscountAdapter.getDataList())) {
            for (SettleCalculatePriceEntity.DiscountItemBean bean : mDiscountAdapter.getDataList()) {
                if (bean.getDiscountType() == SettleCalculatePriceEntity.DiscountItemBean.TYPE_CASH ||
                        bean.getDiscountType() == SettleCalculatePriceEntity.DiscountItemBean.TYPE_BALANCE) {
                    return true;
                }
            }
        }
        return false;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (SUNMI_PAY_ACTION.equals(action) && mPresenter.isSunMiPay()) {
                mPresenter.setSunMiPay(false);
                String jsonStr = intent.getStringExtra("response");
                Elog.e("SUNMI_PAY", "返回参数：" + jsonStr);
                mPresenter.querySmPayOrderInfo(true);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REDEEM_GOODS && resultCode == RESULT_OK) {
            List<GoodsEntity> integralList = (List<GoodsEntity>) data.getSerializableExtra(ACT_Redeem.KEY_REDEEM_GOODS);
            mPresenter.setIntegralList(integralList);
            int totalCount = 0;
            for (GoodsEntity goodsEntity : integralList) {
                totalCount += Integer.parseInt(goodsEntity.getGoodsCount());
            }
            mDiscountMenuAdapter.updateSelectCountByType(DiscountMenuEntity.TYPE_REDEEM, totalCount);
            mDiscountMenuAdapter.notifyDataSetChanged();
        }
    }

    public static void startAc(Context context, String memberPhone, String goodsJson, String orderType, boolean ifGoodsSaved) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        Intent intent = new Intent(context, ACT_SettleAccounts.class);
        Bundle bundle = new Bundle();
        bundle.putString(SETTLE_MEMBER_PHONE, memberPhone);
        bundle.putString(SETTLE_GOODS_JSON, goodsJson);
        bundle.putString(SETTLE_ORDER_TYPE, orderType);
        bundle.putBoolean(SETTLE_GOODS_IF_SAVED, ifGoodsSaved);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_settle_accounts;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog(unBindMemberDialog, cardDialog, couponDialog, activityDialog,
                cashPayDialog, cashChangeDialog, balancePayDialog, payDialog, bankDefaultPayDialog, bankPosPayDialog);
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    public void showPopupHint() {
        btnConfirmPay.post(new Runnable() {
            @Override
            public void run() {

                if (mMemberPopup != null && mMemberPopup.isShowing()) {
                    mMemberPopup.dismiss();
                }

                mMemberPopup = PopupUtil.showBlackBgPopup(mPresenter.isBindMemberForPopup() ? ivUnbindMember : ivAddMember,
                        mPresenter.isBindMemberForPopup() ? PopupUtil.SETTLE_UNBIND_MEMBER : PopupUtil.SETTLE_ADD_MEMBER,
                        mPresenter.isBindMemberForPopup() ? "点击解绑会员" : "点击快捷添加会员", PopupUtil.LEFT_TOP);

                if (btnMl.getVisibility() == View.VISIBLE) {
                    mMlHintPopup = PopupUtil.showBlackBgPopup(btnMl, PopupUtil.SETTLE_ERASE_ZERO, "点击设置抹零金额", PopupUtil.LEFT_BOTTOM);
                }

            }
        });
    }
}
